package org.example.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class JWTUtil {
 
    //以下为自己的配置
    private String secret = "test";
    private String tokenHead = "AiToken";
    private Long expiration = 30L;
 
    /**
     * 生成签名,指定时间后过期,一经生成不可修改，令牌在指定时间内一直有效
     *
     * @return 加密的token
     */
    public String sign(Long userId) {
        try {
            long currentTimeMillis = System.currentTimeMillis();
            Date date = new Date(currentTimeMillis + (expiration * 1000 * 60 * 60 * 24));
 
            Map<String, Object> map = new HashMap<>();
            //设置算法类型
            map.put("alg", "HS256");
            map.put("typ", "JWT");
            //加密算法
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带username信息
            String token = JWT.create()
                    .withHeader(map)//设置头部信息
                    .withAudience("MANAGE")//设置 载荷 签名的观众 也可以理解谁接受签名的
                    //签发时间
                    .withIssuedAt(new Date(currentTimeMillis))
                    .withClaim("userId", userId)
                    //过期时间
                    .withExpiresAt(date)
                    .sign(algorithm);
            if (StringUtils.hasText(token)) {
                token = tokenHead + " " + token;
            }
            return token;
        } catch (Exception e) {
            return null;
        }
    }
 
    //不设置过期时间
 
    public String signForever() {
        try {
            long currentTimeMillis = System.currentTimeMillis();
 
            Map<String, Object> map = new HashMap<>();
            map.put("alg", "HS256");
            map.put("typ", "JWT");
            //加密算法
            Algorithm algorithm = Algorithm.HMAC256(secret);
            // 附带username信息
            String token = JWT.create()
                    .withHeader(map)//设置头部信息
                    .withAudience("MANAGE")//设置 载荷 签名的观众 也可以理解谁接受签名的
                    //签发时间
                    .withIssuedAt(new Date(currentTimeMillis))
                    .sign(algorithm);
            if (StringUtils.hasText(token)) {
                token = tokenHead + " " + token;
            }
            return token;
        } catch (Exception e) {
            return null;
        }
    }

    public Long getUserIdByToken(String token){
        String tokenHead = "AiToken ";  // 这里将 tokenHead 设置为 "AiToken "

        // 检查 token 是否以 "AiToken " 开头并去掉前缀
        if (token.startsWith(tokenHead)) {
            token = token.substring(tokenHead.length()).trim();  // 去除 "AiToken " 和多余的空格
        }
        DecodedJWT decodedJWT = JWT.decode(token);
        // 获取过期时间
        Date expiration = decodedJWT.getExpiresAt();
        // 检查 token 是否过期
        if (expiration != null && expiration.before(new Date())) {
            throw new RuntimeException("Token is expired");
        }
        Long userId = decodedJWT.getClaim("userId").asLong();
        if(userId == null){
            throw new RuntimeException("no userId found by token");
        }
        return userId;
    }
 
}
 